package com.heima.user.interceptor;

import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取登录用户 id
        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId) && Integer.parseInt(userId) != 0){
            //2.将登录用户 id 存放到线程局部变量中
            AppThreadLocalUtils.setUser(Integer.parseInt(userId));
            log.info("请求通过拦截器，当前 APP 端登录用户 id: {}", userId);
        }
        //3.放行请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppThreadLocalUtils.clear();
        log.info("请求即将从 {} 微服务返回，线程局部变量中登录用户 id 已被销毁..", "user-service");
    }
}
